package com.gxxy.spring.kp03_aop.cls01_proxy.s2_dynamic.k02_inherit;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

// 通过实现接口java.lang.reflect.InvocationHandler的方式实现动态的代理 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DynamicProxyTest {

	@Autowired
	private TransactionManager txMgr;

	@Test
	public void testDynamicProxy() throws Exception {
		
		StudentService service = new StudentService();

		ClassLoader loader = StudentService.class.getClassLoader();
		InvocationHandler handler = new TransactionInvocationHandler(service, txMgr);
		
		Enhancer hancer = new Enhancer();
		hancer.setClassLoader(loader);
		hancer.setSuperclass(StudentService.class);
		hancer.setCallback(handler);
		
		StudentService proxy = (StudentService) hancer.create();
		proxy.save(new Student("Rose", 18));
		
	}

}
